<template>
  <div class="add-product-container">
    <div class="page-header">
      <h2>添加新商品</h2>
      <button class="back-btn" @click="goBack">返回商品列表</button>
    </div>

    <form class="product-form" @submit.prevent="submitForm">
      <div class="form-group">
        <label for="productName"
          >商品名称 <span class="required">*</span></label
        >
        <input
          type="text"
          id="productName"
          v-model="product.productName"
          placeholder="请输入商品名称"
        />
      </div>

      <div class="form-group">
        <label for="description"
          >商品描述 <span class="required">*</span></label
        >
        <textarea
          id="description"
          v-model="product.description"
          rows="5"
          placeholder="请输入商品详细描述"
        ></textarea>
      </div>

      <div class="form-group">
        <label for="price">商品价格（元）<span class="required">*</span></label>
        <input
          type="number"
          id="price"
          v-model.number="product.price"
          min="0"
          step="0.01"
          placeholder="请输入商品价格"
          @blur="validatePrice"
        />
      </div>

      <div class="form-group">
        <label for="stock">库存数量 <span class="required">*</span></label>
        <input
          type="number"
          id="stock"
          v-model.number="product.stock"
          min="0"
          placeholder="请输入库存数量"
          @blur="validateStock"
        />
      </div>

      <div class="form-group">
        <label>商品分类 <span class="required">*</span></label>
        <div class="category-selectors">
          <select
            v-model="product.categoryLevel1Id"
            @change="handleLevel1Change"
            :class="{ 'invalid-select': categoryError }"
          >
            <option value="">请选择一级分类</option>
            <option
              v-for="category in level1Categories"
              :key="category.id"
              :value="category.id"
            >
              {{ category.name }}
            </option>
          </select>

          <select
            v-model="product.categoryLevel2Id"
            @change="handleLevel2Change"
            :disabled="!product.categoryLevel1Id"
          >
            <option value="">请选择二级分类</option>
            <option
              v-for="category in level2Categories"
              :key="category.id"
              :value="category.id"
            >
              {{ category.name }}
            </option>
          </select>

          <select
            v-model="product.categoryLevel3Id"
            :disabled="!product.categoryLevel2Id"
          >
            <option value="">请选择三级分类</option>
            <option
              v-for="category in level3Categories"
              :key="category.id"
              :value="category.id"
            >
              {{ category.name }}
            </option>
          </select>
        </div>
        <div v-if="categoryError" class="error-message">
          {{ categoryError }}
        </div>
      </div>

      <div class="form-group">
        <label for="file">商品图片 <span class="required">*</span></label>
        <input
          type="file"
          id="file"
          accept="image/*"
          @change="handleFileChange"
        />
        <div class="preview-container" v-if="picUrl">
          <img :src="picUrl" alt="预览图" class="preview-img" />
        </div>
      </div>

      <div class="form-actions">
        <button type="button" class="cancel-btn" @click="goBack">取消</button>
        <button type="submit" class="submit-btn" :disabled="isSubmitting">
          {{ isSubmitting ? "提交中..." : "添加商品" }}
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "AddProduct",
  data() {
    return {
      categoryError: "",
      product: {
        productName: "",
        description: "",
        price: 0,
        stock: 0,
        categoryLevel1Id: "",
        categoryLevel2Id: "",
        categoryLevel3Id: "",
        fileName: "",
      },
      level1Categories: [],
      level2Categories: [],
      level3Categories: [],
      picUrl: "",
      selectedFile: null,
      isSubmitting: false,
      priceError: "", // 用于显示价格验证错误信息
    };
  },
  created() {
    this.fetchLevel1Categories();
  },
  methods: {
    // 获取一级分类
    async fetchLevel1Categories() {
      try {
        const response = await axios.get("/api/category/getCategoryLevel1Id");
        this.level1Categories = response.data.categoryList;
      } catch (error) {
        console.error("获取一级分类失败:", error);
        this.$message.error("获取分类数据失败");
      }
    },
    // 验证分类选择
    validateCategories() {
      if (!this.product.categoryLevel1Id) {
        this.categoryError = "请选择一级分类";
        this.$message.error("请选择一级分类");
        return false;
      }
      this.categoryError = "";
      return true;
    },
    // 重置表单数据
    resetForm() {
      this.product = {
        productName: "",
        description: "",
        price: 0,
        stock: 0,
        categoryLevel1Id: "",
        categoryLevel2Id: "",
        categoryLevel3Id: "",
        fileName: "",
      };
      this.level2Categories = [];
      this.level3Categories = [];
      this.picUrl = "";
      this.selectedFile = null;
      this.priceError = "";
      // 清除文件输入框的值
      const fileInput = document.getElementById("file");
      if (fileInput) fileInput.value = "";
      this.$message.info("表单已重置");
    },
    // 一级分类变更时获取二级分类
    async handleLevel1Change() {
      this.product.categoryLevel2Id = "";
      this.product.categoryLevel3Id = "";
      this.level2Categories = [];
      this.level3Categories = [];

      if (!this.product.categoryLevel1Id) return;

      try {
        const response = await axios.get(
          `/api/category/getCategoryParent/${this.product.categoryLevel1Id}`
        );
        this.level2Categories = response.data.categoryList;
      } catch (error) {
        console.error("获取二级分类失败:", error);
        this.$message.error("获取二级分类失败");
      }
    },

    // 二级分类变更时获取三级分类
    async handleLevel2Change() {
      this.product.categoryLevel3Id = "";
      this.level3Categories = [];

      if (!this.product.categoryLevel2Id) return;

      try {
        const response = await axios.get(
          `/api/category/getCategoryParent/${this.product.categoryLevel2Id}`
        );
        this.level3Categories = response.data.categoryList;
      } catch (error) {
        console.error("获取三级分类失败:", error);
        this.$message.error("获取三级分类失败");
      }
    },

    // 处理文件上传预览
    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        this.selectedFile = file;
        this.picUrl = URL.createObjectURL(file);
        this.product.fileName = file.name;
      }
    },

    validatePrice() {
      // 获取价格值并转换为字符串
      let price = this.product.price;
      const priceStr = String(price);

      console.log(price);
      // 检查是否为空
      if (price === null || price === undefined || price === "") {
        this.$message.error("价格不能为空也不能字符");
        this.product.price = 1;
        return false;
      }

      // 检查是否为有效数字
      if (
        isNaN(price) ||
        /[a-zA-Z]/.test(priceStr) ||
        /[^0-9.]/.test(priceStr.replace(/\./, ""))
      ) {
        this.$message.error("请输入有效的数字");
        this.product.price = 1;
        return false;
      }

      const num = Number(price);

      // 检查是否为正数
      if (num <= 0) {
        this.$message.error("价格必须大于0");
        this.product.price = 1;
        return false;
      }

      // 检查小数位数
      if ((priceStr.split(".")[1] || "").length > 2) {
        this.$message.error("价格最多只能有两位小数");
        this.product.price = 1.0;
        return false;
      }

      // 格式化合法输入
      this.product.price = parseFloat(num.toFixed(2));
      return true;
    },
    // 验证库存
    validateStock() {
      // 获取库存值并转换为字符串
      let stock = this.product.stock;
      const stockStr = String(stock);

      // 检查是否为空
      if (stock === null || stock === undefined || stock === "") {
        this.$message.error("库存数量不能为空");
        this.product.stock = 1;
        return false;
      }

      // 检查是否为有效整数（排除所有非数字字符）
      if (
        isNaN(stock) ||
        /[a-zA-Z]/.test(stockStr) ||
        /[^0-9]/.test(stockStr) ||
        stockStr.includes(".")
      ) {
        this.$message.error("请输入有效的整数");
        this.product.stock = 1;
        return false;
      }

      const num = parseInt(stock, 10);

      // 检查是否为正数
      if (num < 0) {
        this.$message.error("库存不能为负数");
        this.product.stock = 1;
        return false;
      }

      // 设置合法值
      this.product.stock = num;
      return true;
    },
    // 提交表单
    async submitForm() {
      //检验商品名
      if (!this.product.productName.trim()) {
        this.$message.error("商品名不能为空");
        return;
      }
      if (!this.product.description.trim()) {
        this.$message.error("商品描述不能为空");
        return;
      }

      // 先校验价格
      if (!this.validatePrice()) {
        return;
      }
      // 再校验库存
      if (!this.validateStock()) {
        return;
      }
      if (!this.validateCategories()) {
        return;
      }

      this.isSubmitting = true;
      try {
        // 创建FormData处理文件上传
        const formData = new FormData();
        formData.append("productName", this.product.productName);
        formData.append("description", this.product.description);
        formData.append("price", this.product.price);
        formData.append("stock", this.product.stock);
        formData.append("categoryLevel1Id", this.product.categoryLevel1Id);
        formData.append("categoryLevel2Id", this.product.categoryLevel2Id);
        formData.append("categoryLevel3Id", this.product.categoryLevel3Id);

        // 图片可选，如果有则添加
        if (this.selectedFile) {
          formData.append("file", this.selectedFile);
        }

        await axios.post("/api/product/addProduct", formData);
        this.$message.success("商品添加成功");
        this.goBack();
      } catch (error) {
        console.error("添加商品失败:", error);
        this.$message.error(
          `添加失败: ${error.response?.data?.message || error.message}`
        );
      } finally {
        this.isSubmitting = false;
      }
    },

    // 价格输入变化时验证
    onPriceChange() {
      this.validatePrice();
    },
    // 返回商品列表
    goBack() {
      this.$router.push({ name: "ProductList" });
    },
  },
};
</script>

<style scoped>
.add-product-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.back-btn {
  padding: 8px 15px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.product-form {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #ff4d4f;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group textarea {
  resize: vertical;
  min-height: 120px;
}

.category-selectors {
  display: flex;
  gap: 15px;
}

.category-selectors select {
  flex: 1;
}

.preview-container {
  margin-top: 10px;
}

.preview-img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
}

.cancel-btn {
  padding: 9px 18px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn:hover {
  background-color: #e6e6e6;
}

.submit-btn {
  padding: 9px 18px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.submit-btn:hover:not(:disabled) {
  background-color: #40a9ff;
}

.submit-btn:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}
</style>